#ifndef EVENT_DETECTION
#define EVENT_DETECTION

#include "configuration.h"
#include "adc.h"
#include "timer.h"

unsigned int lineCount = 0;

//Cross current signal detection using rising edge
bool crossDetection()
{
    static unsigned int lastMidReading = 0;
    unsigned int midReading = getAnalog(MID_SENSOR);
    static char debounce = 0;

    if (!debounce && midReading >= READING_THRESH_MID && lastMidReading < READING_THRESH_MID)
    {
        debounce = 80;
        lastMidReading = midReading;
        return true;
    }
    else
    {
        if (debounce) --debounce;
        lastMidReading = midReading;
        return false;
    }
}

int eventManagerUpdate(int diff)
{
    int tempState = STRAIGHT;
    static int eventTime = 0;
    static int timeToStop = BLIND_TIME_LIMIT;

    if (getAnalog(LEFT_SENSOR) < READING_THRESH && 
        getAnalog(RIGHT_SENSOR) < READING_THRESH && 
        getAnalog(MID_SENSOR) < READING_THRESH)  //No signal detected
    {
        if (timeToStop < diff)
            tempState = STOP;
        else
            timeToStop -= timeToStop;
    }
    else
    {
        timeToStop = BLIND_TIME_LIMIT;

        if (crossDetection()) //low high transition, a line is crossed
        {
            ++lineCount;
            eventTime = EVENT_INTERVAL_TIME;
            if (lineCount >= 4) // start: handle immediately
                eventTime = 0;
        }

        eventTime -= diff;

        if (eventTime < diff)  //Inspection time loop expires
        {
            switch (lineCount)
            {
                case 0:
                case 1: tempState = STRAIGHT; break;
                case 2: tempState = LEFT; break;
                case 3: tempState = RIGHT; break;
                default: tempState = START; break;
            }
            lineCount = 0;
            eventTime = 0;
        }
    }
    return tempState;    
}

#endif
